from django.db import models

from apps.users.models import User
from utils.models import BaseModel


# Create your models here.


class Category(BaseModel):
    name = models.CharField(max_length=20, unique=True, verbose_name='分类名称')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tb_article_category'
        verbose_name = '文章内容表'
        verbose_name_plural = verbose_name


class Article(BaseModel):
    title = models.CharField(max_length=50, verbose_name='文章标题')
    clicks = models.IntegerField(verbose_name='浏览量', default=0)
    category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='articles', verbose_name='文章分类')
    author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='articles', verbose_name='作者')
    collection_users = models.ManyToManyField(User, verbose_name='收藏用户', related_name='collection_articles')

    @property
    def ctime(self):
        return int(self.create_time.timestamp() * 1000)

    @property
    def comment_count(self):
        return self.comments.count()

    class Meta:
        db_table = 'tb_articles'
        verbose_name = '文章'
        verbose_name_plural = verbose_name
        ordering = ('-clicks', '-create_time')

    def __str__(self):
        return self.title


class ArticleContent(BaseModel):
    content = models.TextField(verbose_name='文章内容')
    article = models.OneToOneField(Article, on_delete=models.CASCADE, verbose_name='文章', related_name='content')

    class Meta:
        db_table = 'tb_article_content'
        verbose_name = '文章内容表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content


class ArticleImages(BaseModel):
    url = models.CharField(max_length=255, verbose_name='文章图片')
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='images', verbose_name='文章')

    class Meta:
        db_table = 'tb_article_images'
        verbose_name = '文章图片表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.url
